const Core = require("@alicloud/pop-core");
const dayjs = require("dayjs");
const jwt = require("jsonwebtoken");
const accessKeyId = "LTAI5t6BMc3wuGpTtoU5YsPz"; //你自己在阿里云后台的accessKeyId
const secretAccessKey = "fiVXcsamw91cCX9n32y8infVgUj3jL"; //secretAccessKey

const client = new Core({
    accessKeyId: accessKeyId,
    secretAccessKey: secretAccessKey,
    endpoint: "https://dysmsapi.aliyuncs.com",
    apiVersion: "2017-05-25",
});
function getParams(phone, code) {
    return {
        RegionId: "cn-hangzhou",
        PhoneNumbers: phone, // 手机号
        SignName: "活动帮", // 短信签名
        TemplateCode: "SMS_473365011", // 短信模板 ID
        TemplateParam: '{"code":"' + code + '" }',
    };
}

exports.code = async (req, res) => {
    const phoneRegex = /^(?:(?:\+|00)86|86)?1\d{10}$/;
    const isValidPhone = (phone) => phoneRegex.test(phone);
    const { body } = req;
    if(!body.phone){
        return res.send({
            code: 0,
            msg: "请输入手机号",
        });
    }else if(!isValidPhone(body.phone)){
        return res.send({
            code: 0,
            msg: "请输入正确的手机号",
        });
    }
    const redisData = await global.connectRedis.get(body.phone);
    if (redisData) {
        res.send({
            code: 0,
            msg: "您的验证码依然有效不需要重新发送",
            codeMa: redisData
        });
    } else {
        const code = Math.floor(Math.random() * 9000 + 1000); // 生成 4 位随机验证码
        global.connectRedis.set(body.phone, code, "EX", 5 * 60);
        const params = getParams(body.phone, code);
        const requestOption = {
            method: "POST",
        };
        try {
            const result = await client.request("SendSms", params, requestOption);
            res.send({
                code: 200,
                msg: "发送成功",
            });
        } catch (err) {
            console.error(err);
            res.send({
                code: 0,
                msg: "发送失败",
            });
        }
    }


}
exports.register = async (req, res) => {
    const create_time = dayjs().format("YYYY-MM-DD HH:mm:ss");
    const { name, phone, firm, dept, code } = req.body;
    if(!phone){
        return res.send({
            code: 0,
            msg: "请输入手机号",
        });
    }
    if(!code){
        return res.send({
            code: 0,
            msg: "请输入验证码",
        });
    }
    if(!name){
        return res.send({
            code: 0,
            msg: "请输入昵称",
        });
    }
    if(!firm){
        return res.send({
            code: 0,
            msg: "请输入公司",
        });
    }
    if(!dept){
        return res.send({
            code: 0,
            msg: "请输入部门",
        });
    }
    const redisData = await global.connectRedis.get(phone);
    if (redisData && code == redisData) {
        const sqlPhone = `SELECT * from  users WHERE phone=?`;
        const sqlPhoneRes = await global.query(sqlPhone, [phone])
        if (sqlPhoneRes && sqlPhoneRes.length > 0) {
            res.send({
                code: 0,
                msg: "您已经注册了请不要重新注册！",
            });
        } else {
            const tokenStr = jwt.sign({ phone }, process.env.SECRET_KEY, {
                expiresIn: process.env.EXPIRESIN,
            });
            global.connectRedis.set(tokenStr, phone, "EX", 24 * 100 * 60 * 60);

            const sql = `INSERT INTO users(name,phone,firm,dept,create_time) VALUES(?,?,?,?,?)`;
            const sqlRes = await global.query(sql, [name, phone, firm, dept, create_time])
            if (sqlRes.affectedRows) {
                res.send({
                    code: 200,
                    msg: "添加成功",
                    token: "Bearer " + tokenStr,
                });
            } else {
                res.send({
                    code: 0,
                    msg: "添加失败",
                });
            }
        }

    } else if (redisData && code != redisData) {
        res.send({
            code: 0,
            msg: "验证码错误",
        });
    } else {
        res.send({
            code: 0,
            msg: "验证码已过期，请重新发送验证码",
        });
    }

}
exports.login = async (req, res) => {
    const { phone } = req.body;
    const tokenStr = jwt.sign({ phone }, process.env.SECRET_KEY, {
        expiresIn: process.env.EXPIRESIN,
    });
    global.connectRedis.set(tokenStr, phone, "EX", 24 * 100 * 60 * 60);
    const sql = `SELECT * from  users WHERE phone=?`;
    const sqlRes = await global.query(sql, [phone])
    if (sqlRes.length > 0) {
        res.send({
            code: 200,
            msg: "登录成功",
            token: "Bearer " + tokenStr,
        });
    } else {
        res.send({
            code: 0,
            msg: "登录失败",
        });
    }

}


exports.works = async (req, res) => {
    const { type } = req.query
    if (!type || (type != "likes" && type != "hot" && type != "red")) {
        return res.send({
            code: 0,
            msg: "type 必须的",
        });

    }
    const sql = `SELECT * from  works order by  ${type} desc`;
    const sqlRes = await global.query(sql, [])
    if (sqlRes.length > 0) {
        res.send({
            code: 200,
            msg: "登录成功",
            list: sqlRes
        });
    } else {
        res.send({
            code: 0,
            msg: "登录失败",
        });
    }
}
exports.add = async (req, res) => {
    const create_time = dayjs().format("YYYY-MM-DD HH:mm:ss");
    const { w_type,w_url,w_link,title, description,likes, hot, red } = req.body
    console.log("req.body", req.body)
    const sql = `INSERT INTO works(w_type,w_url,w_link,title,description,likes,hot,red,create_time) VALUES(?,?,?,?,?,?,?,?,?)`;
    const sqlRes = await global.query(sql, [w_type,w_url,w_link,title, description, likes, hot, red, create_time])
    if (sqlRes.affectedRows) {
        res.send({
            code: 200,
            msg: "添加成功",
        });
    } else {
        res.send({
            code: 0,
            msg: "添加失败",
        });
    }
}

exports.edit = async (req, res) => {
    const { likes, hot, red, id } = req.body
    let sql = "";
    if (likes == 1) {
        sql = `UPDATE works SET likes = likes + 1 WHERE id = ?`;
    } else if (hot == 1) {
        sql = `UPDATE works SET hot= hot + 1  WHERE id = ?`;
    } else if (red == 1) {
        sql = `UPDATE works SET red= red + 1 WHERE id = ?`;
    }

    const sqlRes = await global.query(sql, [id])
    if (sqlRes.affectedRows) {
        res.send({
            code: 200,
            msg: "点赞成功",
        });
    } else {
        res.send({
            code: 0,
            msg: "点赞失败",
        });
    }
}

